import wepy from 'wepy'

const KEY = 'GOODS'

/**
 * 往Storage中增加商品
 * @param {} goods {goods_id:140,goods_number:2}
 * 最终保存在本地的样子
 *  {140:3,395:3}
 */
const saveGoods = goods => {
  // 1.取出原先保存的商品对象
  // localGoods取出来长成这个样子 {140:3,395:3}
  const localGoods = wepy.getStorageSync(KEY) || {}

  // 2.遍历localGoods,查看localGoods是否有key存在，如果商品数量就累加，如果不存在就新增一个
  if(localGoods[goods.goods_id]){
    localGoods[goods.goods_id] = localGoods[goods.goods_id] + goods.goods_number
  }else{
    localGoods[goods.goods_id] = goods.goods_number
  }

  // 保存回去
  wepy.setStorageSync(KEY, localGoods)
}

// 修改本地商品数量
const updateGoods = goods => {
  // 1.取出原先保存的商品对象
  // localGoods取出来长成这个样子 {140:3,395:3}
  const localGoods = wepy.getStorageSync(KEY) || {}

  // 修改数量
  localGoods[goods.goods_id] = goods.goods_number

  // 保存回去
  wepy.setStorageSync(KEY, localGoods)
}

// 根据商品id删除商品信息
const deleteGoodsById = goods_id => {
  // 1.取出原先保存的商品对象
  // localGoods取出来长成这个样子 {140:3,395:3}
  const localGoods = wepy.getStorageSync(KEY) || {}

  // 2.干掉原先商品中的商品信息
  delete localGoods[goods_id]

  // 保存回去
  wepy.setStorageSync(KEY, localGoods)
}

// 按需导出
export { saveGoods, updateGoods,deleteGoodsById }
